<template>
  <a-modal
    :title="title"
    :width="800"
    :visible="visible"
    :confirmLoading="confirmLoading"
    @cancel="handleCancel"
    :maskClosable="false"
  >
    <template slot="footer">
      <a-button key="取消" @click="handleCancel">取消</a-button>
      <a-button
        type="primary"
        :loading="loginBtn"
        @click="handleImport"
        :disabled="loginBtn">开始导入</a-button>
    </template>

    <a-steps size="small" :current="current" style="margin: 30px 10px" :status="stepStatus">
      <a-step title="上传文档"/>
      <a-step title="导入数据"/>
      <a-step title="导入结果"/>
    </a-steps>

    <a-form style="margin-left: 20px">
      <a-form-item label="一、请按照数据模板的格式准备要导入的数据" >
        <div style="margin-left: 30px">
          <a @click="handleDownTemplate()" icon="arrow-down" style="width:400px">下载数据模板</a><br/>
          <span>注意事项:</span><br/>
          <p style="margin-bottom: 0px;line-height: 20px;">1、模板中的表头名称不可更改，表头行不能删除</p>
          <p style="margin-bottom: 0px;line-height: 20px;">2、导入文件过大时，处理时间可能较长请耐心等待!</p>
        </div>
      </a-form-item>
      <a-form-item label="二、请选择需要导入的excel文件">
        <a-upload
          name="file"
          :multiple="false"
          :action="uploadFileUrl"
          :headers="fileHeader"
          :fileList="fileList"
          accept=".xls,.xlsx"
          :remove="handleRemove"
          @preview="downloadFile"
          @change="handleFileChange">
          <a-input style="width:200px;margin-left: 30px" placeholder="选择文件"></a-input>
        </a-upload>
      </a-form-item>
    </a-form>

  </a-modal>

</template>

<script>
  import { postAction, downFile } from '@/api/manage'
  import Vue from 'vue'
  import { ACCESS_TOKEN } from '@/store/mutation-types'
  import { getAction } from '../../api/manage'

  export default {
    name: 'ExportModel',
    components:{

    },
    props:{
      title:{
        type:String,
        default:'导入'
      },
      params:{
        type:Object,
        required:false,
        default:function () {
          return {};
        }
      },
      importUrl:{
        type:String,
        required:true,
        default:'导入'
      },
      templateFileName:{
        type:String,
        required:true,
        default:''
      },
      templateUrl:{
        type:String,
        required:true,
        default:''
      },
    },
    data() {
      return {
        loginBtn: false,
        stepStatus: 'wait',
        current: 0,
        visible: false,
        confirmLoading: false,
        loading: true,
        description: '导入',
        fileHeader: { 'X-Access-Token': Vue.ls.get(ACCESS_TOKEN) },
        fileList: [],
        labelCol: {
          xs: { span: 24 },
          sm: { span: 5 }
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 16 }
        },
        url: {
          downTemplateFile:'/sys/common/downTemplate',  //下载公共指定模版
          downLocalFile:'/sys/common/downLocalFile',    //下载服务器文件
          uploadFileUrl:'/sys/common/uploadLocalFile'   //上传文件到到服务器
        }
      }
    },
    computed: {
      uploadFileUrl: function() {
        return `${window._CONFIG['domianURL']}/${this.url.uploadFileUrl}`
      }
    },
    methods: {
      show() {
        this.visible = true
      },
      handleImport() {
        const that = this
        if (that.fileList != null && that.fileList.length > 0) {
          that.loginBtn = true;
          this.current = 2
          that.stepStatus = ''
          that.loginBtn = true;
          let params = Object.assign(that.params,{filename: that.fileList[0].name, filepath: that.fileList[0].url});
            getAction(this.importUrl,params).then((res) => {
            if (res.success) {
              that.loginBtn = false;
              that.stepStatus = 'finish'
              that.$message.success(res.message)
              that.$emit('ok')
              that.close()
            } else {
              that.loginBtn = false;
              that.$message.warning(res.message)
              that.stepStatus = 'error'
            }
          })
        }
      },
      handleCancel() {
        const that = this
        that.loginBtn = false;
        this.close()
      },
      close() {
        this.fileList = []
        this.$emit('close')
        this.visible = false
        this.current = 0
        this.stepStatus = 'wait'
      },
      handleDownTemplate() {
        this.tempalteDownloadFile(this.templateFileName);
      },
      // 文件上传方法
      handleFileChange(info) {
        let fileList = [...info.fileList]
        fileList = fileList.slice(-1)
        fileList = fileList.map((file) => {
          if (file.response) {
            file.url = file.response.result.filepath
            file.name = file.response.result.filename
            this.current = 1
            this.stepStatus = 'finish'
          } else {
            this.current = 0
            this.stepStatus = 'error'
          }
          return file
        })
        this.fileList = fileList
      },
      downloadFile(file) {
        downFile(this.url.downLocalFile, { filepath: file.url, filename: file.name }).then((data) => {
          if (!data) {
            this.$message.warning('文件下载失败')
            return
          }
          if (typeof window.navigator.msSaveBlob !== 'undefined') {
            window.navigator.msSaveBlob(new Blob([data]), file.name)
          } else {
            let url = window.URL.createObjectURL(new Blob([data]))
            let link = document.createElement('a')
            link.style.display = 'none'
            link.href = url
            link.setAttribute('download', file.name)
            document.body.appendChild(link)
            link.click()
            document.body.removeChild(link); // 下载完成移除元素
            window.URL.revokeObjectURL(url); // 释放掉blob对象
          }
        })
      },
      tempalteDownloadFile(fileName) {
        let params = {};
        let downTemplateUrl = "";
        if(this.templateUrl){
          //使用导出excel作为模版
          params.excelTemplate = true
          params.templateName = fileName;
          downTemplateUrl = this.templateUrl;
        }else {
          //下载指定模版
          params.templateName = fileName
          downTemplateUrl = this.url.downTemplateFile;
        }
        downFile(downTemplateUrl,params).then((data) => {
          if (!data) {
            this.$message.warning('文件下载失败')
            return
          }
          if (typeof window.navigator.msSaveBlob !== 'undefined') {
            window.navigator.msSaveBlob(new Blob([data]), fileName)
          } else {
            let url = window.URL.createObjectURL(new Blob([data]))
            let link = document.createElement('a')
            link.style.display = 'none'
            link.href = url
            link.setAttribute('download', fileName)
            document.body.appendChild(link)
            link.click()
            document.body.removeChild(link); // 下载完成移除元素
            window.URL.revokeObjectURL(url); // 释放掉blob对象
          }
        })
      },
      handleRemove(file) {
        const index = this.fileList.indexOf(file);
        const newFileList = this.fileList.slice(-1);
        newFileList.splice(index, 1);
        this.fileList = newFileList
        this.current = 0
        this.stepStatus = 'wait'
      }
    }
  }
</script>

<style scoped>

</style>
